<template>
  <div class="container">
    <div class="pdf-preview" ref="PDFViewRef">
      <!-- PDF预览内容 -->
      <Tool ref="toolRef" @clickEvent="clickEventFn"></Tool>
      <div id="pdf-container"></div>
    </div>
    <div class="feedback-dropdown">
      <!-- 意见反馈下拉框 -->
      <ul>
        <li
          class="annotation"
          v-for="item in feedbackData"
          :key="item.id"
          :data-page="item.page"
          :data-id="item.id"
          :class="{ active: feedbackState.uuid === item.uuid }"
          :style="{
            backgroundColor: getBackgroundFn(item.status),
          }"
          @click="stickyCanvasFn(item.page, item)"
        >
          <div class="header">
            <span class="type"
              >类型：<span>{{ item.type }}</span></span
            >
            <i
              class="fa fa-trash delete"
              @click.stop="delFeedbackFn(item.page, item.id, item.uuid)"
              ><span>删除</span></i
            >
          </div>
          <div class="commit"></div>
          <div class="info">
            <div class="user">{{ item.createUser }}</div>
            <div class="time">{{ item.createTime }}</div>
          </div>
        </li>
      </ul>
    </div>
    <!-- <div class="richtext-editor" v-loading="isLoading"> -->
    <div class="richtext-editor">
      <!-- 聊天消息区域 -->
      <div class="chat-messages">
        <div
          v-for="item in richData"
          :key="item.id"
          :class="['message', item.type]"
        >
          <span>{{ item.createUser }} </span>
          <div class="message-content">
            <Richtext :textHtml="item.amendBody" :readOnly="true" />
          </div>
        </div>
      </div>

      <!-- 回复区域 -->
      <div
        class="reply"
        v-if="richData.length !== 2 || richData?.[0]?.adminFlag"
      >
        <Richtext ref="richTextRef" />
        <button
          class="btn"
          @click="updateRichTextFn()"
          v-if="richData.length === 0"
        >
          发送
        </button>
        <template v-else>
          <button class="reject-btn" @click="responseAmendFn(0)">拒绝</button>
          <button class="btn" @click="responseAmendFn(1)">同意</button>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import Richtext from "./component/RichText.vue";
import Tool from "./component/Tool.vue";
import { onMounted, ref, watch } from "vue";
import { PDFAnnotate } from "./js";
import { useRoute } from "vue-router";
import axios from "axios";
import { reactive } from "vue";
const route = useRoute();
const isLoading = ref(false);

import { getAmendDataFn, getAmendDetailDataFn } from "../../axios/index";

const feedbackState = reactive({
  id: "",
  uuid: "",
  amendId: "",
});

const feedbackData = ref([]);
const loadDataFn = (totalPage) => {
  const pageJson = {
    pages: [],
  };
  for (let i = 0; i < totalPage; i++) {
    const json = {
      version: "4.3.0",
      objects: [],
    };
    feedbackData.value.forEach((item) => {
      if (item.page - 1 === i) {
        json.objects.push(JSON.parse(item.taggedBody));
      }
    });
    pageJson.pages.push(json);
  }
  return pageJson;
};

// 0 拒绝 1 同意 2 未审批
const getBackgroundFn = (status) => {
  switch (status) {
    case 0:
      return "#FF6B6B";
    case 1:
      return "#66BB6A";
    case 2:
      return "#BDBDBD";
  }
};

let PDFContainer = null;
const initFlag = ref(false);
const initFn = (fileUrl) => {
  PDFContainer = new PDFAnnotate("pdf-container", fileUrl, {
    onPageUpdated(page, oldData, newData) {
      if (!initFlag.value) {
        console.log(newData);
        toolRef.value.tool = "selector";
        // if (newData.type === "lineArrow") return;
        PDFContainer.enableSelector();
        createFeedbackFn(page, newData);
      }
    },
    ready() {
      initFlag.value = true;
      const loadData = loadDataFn(PDFContainer.number_of_pages);
      console.log(loadData);
      PDFContainer.loadFromJSON(loadData);
    },
    initFinish() {
      initFlag.value = false;
    },
    mousedownFn(target, fabricObjects, page) {
      if (target) {
        const fabricObject = fabricObjects[page];
        feedbackState.uuid = target.customData.id;
        fabricObject.setActiveObject(target, "mouse:down");
        fabricObject.renderAll();
        getAmendDetailByUUIDFn();
      } else {
        // currentAnnotationId.value = "";
      }
    },
    scale: 1.5,
    pageImageCompression: "MEDIUM", // FAST, MEDIUM, SLOW(Helps to control the new PDF file size)
  });
};

/**
 *
 * 创建回复和画布
 * 此处和你本身业务数据有关，这是样例数据
 *
 */
const createFeedbackFn = (page, data) => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "");
  feedbackData.value.push({
    id: null,
    uuid: data.customData && data.customData.id,
    page,
    fileId: route.query.fileId,
    type: data.type,
    createUser: userInfo.userName,
    createTime: new Date().getTime(),
    num: 1,
  });
  setTimeout(() => {
    saveCanvasFn();
  }, 100);
};

/* 删除评论和画布数据 */
const delFeedbackFn = (page, id, uuid) => {
  const fabricObjects = PDFContainer.fabricObjects[page - 1];
  const delEle = fabricObjects
    .getObjects()
    .find((item) => item.customData.id === uuid);
  if (confirm("Are you sure ?")) {
    fabricObjects.remove(delEle);
    feedbackData.value = feedbackData.value.filter(
      (item) => item.uuid !== uuid
    );
  }
  if (id) {
    axios
      .get(`/skr/amendFile/deleteAmend/${id}`, {
        headers: {
          Authorization: Authorization,
        },
      })
      .then((response) => {
        // Handle the response data
        console.log(response.data);
        console.log("删除成功");
      });
  }
};

const PDFViewRef = ref();
const stickyCanvasFn = (page, item) => {
  // 获取右侧聊天详情
  feedbackState.id = item.id;
  feedbackState.uuid = item.uuid;
  getAmendDetailByUUIDFn();

  // 高亮
  const fabricObject = PDFContainer.fabricObjects[page - 1];
  const canvases = fabricObject.getObjects();
  const currentCas = canvases.filter(
    (canvas) => canvas.customData.id === item.uuid
  );
  if (currentCas.length > 0) {
    // 滚到当前元素位置
    const center = currentCas[0].getCenterPoint();
    PDFViewRef.value.scrollTop =
      (page - 1) * fabricObject.getElement().clientHeight +
      center.y -
      fabricObject.getElement().clientHeight / 2;

    // 选中该元素
    fabricObject.setActiveObject(currentCas[0], "mouse:down");
    fabricObject.renderAll();
  }
};

// 触发的事件
const toolRef = ref(null);
const clickEventFn = (item) => {
  if (item.type === "tool") {
    if (item.value === "selector") {
      PDFContainer.enableSelector();
    } else if (item.value === "pencil") {
      PDFContainer.enablePencil();
    } else if (item.value === "text") {
      PDFContainer.enableAddText();
    } else if (item.value === "arrow") {
      PDFContainer.enableAddArrow(function () {
        const toolButton = document.querySelector(".tool-button");
        const icon = toolButton.querySelector("i");
        if (icon) {
          icon.click();
        }
      });
    } else if (item.value === "rectangle") {
      PDFContainer.setColor("rgba(255, 0, 0, 0.3)");
      PDFContainer.setBorderColor("blue");
      PDFContainer.enableRectangle();
    } else if (item.value === "image") {
      PDFContainer.addImageToCanvas();
    }
  } else if (item.type === "fn") {
    if (item.value === "import") {
      PDFContainer.savePdf();
    } else if (item.value === "save") {
      // PDFContainer.serializePdf((string) => {
      //   saveCanvasFn(JSON.parse(string));
      // });
      // saveCanvasFn();
    }
  } else if (item.type === "color") {
    PDFContainer.setColor(item.value);
  } else if (item.type === "brushSize") {
    PDFContainer.setBrushSize(item.value);
  } else if (item.type === "fontSize") {
    PDFContainer.setFontSize(item.value);
  }
};
// 保存
const saveCanvasFn = async () => {
  PDFContainer.serializePdf((string) => {
    const canvasData = JSON.parse(string);
    const saveData = [];
    feedbackData.value.map((item) => {
      const taggedBody = canvasData.pages[item.page - 1].objects.find(
        ($item) => {
          if ($item.customData.id === item.uuid) {
            return $item;
          }
        }
      );
      const json = {
        id: item.id,
        uuid: item.uuid,
        page: item.page,
        num: 1,
        fileId: route.query.fileId,
        type: item.type,
        taggedBody: JSON.stringify(taggedBody),
      };
      saveData.push(json);
    });

    axios
      .post(`/skr/amendFile/addAmend`, JSON.stringify(saveData), {
        headers: {
          Authorization: Authorization,
          "Content-Type": "application/json; charset=utf-8",
        },
      })
      .then(() => {
        // console.log("保存成功");
        getfeedbackDataFn();
      });
  });
};
// 获取文件---可以是文件流自己处理，也可以直接是url
const getFileUrlFn = () => {
  function createUrl(content) {
    let blob = new Blob([content], {
      type: "application/pdf",
    });
    return URL.createObjectURL(blob);
  }
  // axios
  //   .post(
  //     `/skr/doc/getFileContent?id=${route.query.fileId}&type=1`,
  //     {},
  //     {
  //       responseType: "blob",
  //       headers: {
  //         Authorization: Authorization,
  //       },
  //     }
  //   )
  // .then((res) => {
  // const url = createUrl(res.data)
  // initFn(url);
  initFn("/example.pdf");
  // });
};
// 获取评论列表
const getfeedbackDataFn = () => {
  const res = getAmendDataFn();
  // axios
  //   .get(`/skr/amendFile/getAmend/${route.query.fileId}`, {
  //     headers: {
  //       Authorization: Authorization,
  //     },
  //   })
  //   .then((res) => {
  feedbackData.value = res.data.data;
  if (res.data.data && res.data.data.length > 0) {
    feedbackState.uuid = feedbackState.uuid || res.data.data[0].uuid;
    feedbackState.id = feedbackState.id || res.data.data[0].id;
    getAmendDetailByUUIDFn();
  }
  // });
};
// 查询详情
const richData = ref([]);
const getAmendDetailByUUIDFn = () => {
  isLoading.value = true;
  const res = getAmendDetailDataFn(feedbackState.uuid);
  // axios
  //   .get(`/skr/amendFile/getAmendDetailByUUID?uuid=${feedbackState.uuid}`, {
  //     headers: {
  //       Authorization: Authorization,
  //     },
  //   })
  //   .then((res) => {
  if (res.data.data) {
    richData.value = res.data.data || [];
    feedbackState.amendId = res.data.data[0]?.id;
  } else {
    richData.value = [];
  }
  isLoading.value = false;
  // });
};
// 保存首次评论
const richTextRef = ref();
const updateRichTextFn = () => {
  const json = {
    id: null,
    uuid: feedbackState.uuid,
    amendBody: richTextRef.value.valueHtml,
  };
  axios
    .post(`/skr/amendFile/updateAmend`, JSON.stringify(json), {
      headers: {
        Authorization: Authorization,
        "Content-Type": "application/json; charset=utf-8",
      },
    })
    .then(() => {
      console.log("发送成功");
      getfeedbackDataFn();
      richTextRef.value.valueHtml = "";
    });
};
// 回复
const responseAmendFn = (status) => {
  const json = {
    id: null,
    amendId: feedbackState.amendId,
    responseBody: richTextRef.value.valueHtml,
    status,
  };
  axios
    .post(`/skr/amendFile/response`, JSON.stringify(json), {
      headers: {
        Authorization: Authorization,
        "Content-Type": "application/json; charset=utf-8",
      },
    })
    .then(() => {
      console.log("回复成功");
      getfeedbackDataFn();
      richTextRef.value.valueHtml = "";
    });
};

// watch(
//   () => route.query.fileId,
//   async (fileId) => {
//     if (fileId) {
//       await getfeedbackDataFn();
//       await getFileUrlFn();
//     } else {
//       message.warning("没有文件id");
//     }
//   },
//   {
//     immediate: true,
//   }
// );
onMounted(async () => {
  await getfeedbackDataFn();
  await getFileUrlFn();
});
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
}
/* 滚动条整体样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

/* 滚动条轨道样式 */
::-webkit-scrollbar-track {
  background-color: transparent;
  border-radius: 4px;
}

/* 滚动条滑块样式 */
::-webkit-scrollbar-thumb {
  background-color: #dcdcdc;
  border-radius: 4px;
  border: 1px solid #f1f1f1;
}

/* 当鼠标悬浮在滚动条滑块上时的样式 */
::-webkit-scrollbar-thumb:hover {
  background-color: #c1c1c1;
}
.pdf-preview {
  position: relative;
  width: 60%;
  background-color: #f5f5f5;
  overflow: auto;
}
.feedback-dropdown {
  width: 12%;
  background-color: #ddd;
  overflow: auto;
  padding: 4px;
}
.richtext-editor {
  width: 28%;
  background-color: #fff;
  overflow: auto;
  position: relative;
  display: flex;
  flex-direction: column;
}
/* 聊天消息区域样式 */
.chat-messages {
  padding: 10px;
  height: 0;
  flex: 1;
  overflow-y: auto;
}

/* 单条消息样式 */
.message {
  display: flex;
  margin-bottom: 10px;
}

/* 接收的消息样式 */
.received {
  justify-content: flex-start;
}

/* 发送的消息样式 */
.sent {
  justify-content: flex-end;
}

/* 消息内容样式 */
.message-content {
  background-color: #eee;
  padding: 8px;
  border-radius: 5px;
  width: 100%;
  position: relative;
}

/* 接收的消息内容样式 */
.received .message-content {
  margin-left: 10px;
}

/* 发送的消息内容样式 */
.sent .message-content {
  margin-right: 10px;
}

/* 消息内容前的三角形 */
.message-content:before {
  content: "";
  position: absolute;
  top: 9px;
  width: 0;
  height: 0;
  border-style: solid;
}

/* 接收的消息三角形样式 */
.received .message-content:before {
  left: -5px;
  border-width: 5px 10px 5px 0;
  border-color: transparent #0163f7 transparent transparent;
}

/* 发送的消息三角形样式 */
.sent .message-content:before {
  right: -5px;
  border-width: 5px 0 5px 10px;
  border-color: transparent transparent transparent #0163f7;
}

/* 回复区域样式 */
.reply {
  overflow: hidden;
  height: 400px;
  padding: 10px;
  background-color: #fff;
}
.reply .btn {
  position: absolute;
  bottom: 30px;
  right: 30px;
}

.reply .btn {
  background-image: linear-gradient(to right, #649bff, #0029ff);
  color: white;
  padding: 10px 20px;
  font-size: 16px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  margin: 4px 2px;
  cursor: pointer;
  border: none;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s, transform 0.1s;
}

/* 鼠标悬停时的按钮样式 */
.reply .btn:hover {
  background-image: linear-gradient(to right, #4f87ff, #0040ff);
  transform: translateY(-2px);
}

/* 鼠标按下时的按钮样式 */
.reply .btn:active {
  background-image: linear-gradient(to right, #3a6fff, #0030ff);
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.reject-btn {
  position: absolute;
  bottom: 30px;
  right: 130px;
  background-image: linear-gradient(to right, #bd4747, #ff0404);
  color: white;
  padding: 10px 20px;
  font-size: 16px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  margin: 4px 2px;
  cursor: pointer;
  border: none;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s, transform 0.1s;
}

.reject-btn:hover {
  background-image: linear-gradient(to right, #bd4747, #ff0404);
  transform: translateY(-2px);
}

.reject-btn:active {
  background-image: linear-gradient(to right, #bd4747, #ff0404);
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(254, 2, 2, 0.2);
}

/* 基础样式 */
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  margin-bottom: 10px;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.header .type {
  font-weight: bold;
}

.description-detail {
  display: block;
  width: 100%;
  padding: 8px;
  border: none;
  background-color: #1890ff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
}

.description-detail:hover {
  background-color: #40a9ff;
}

.info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.user,
.time {
  font-size: 0.9em;
  color: #666;
}

/* 
  pdf
*/
#pdf-container canvas,
.canvas-container {
  margin-bottom: 25px;
}

#pdf-container .canvas-container {
  margin-left: auto;
  margin-right: auto;
}

#pdf-container {
  width: 100%;
  height: 100%;
}

.annotation {
  cursor: pointer;
  transition: background-color 0.3s ease; /* 添加过度动画，持续时间为0.3秒，动画效果为ease */
}

.annotation .delete {
  color: rgb(247, 94, 94); /* 初始颜色 */
  transition: color 0.5s ease; /* 添加过度动画，持续时间为0.3秒，动画效果为ease */
}

.annotation .delete:hover {
  color: red; /* 鼠标悬停时的颜色 */
}

.annotation .delete span {
  margin-left: 4px;
}

.annotation.active {
  background-color: #fff;
  border: 6px solid rgb(255, 255, 255);
}
.annotation:hover {
  background-color: #eee;
}
</style>
